//
//  ViewController.m
//  轻量级TableView
//
//  Created by 徐益智 on 16/4/14.
//  Copyright © 2016年 Vdianjing. All rights reserved.
//

#import "ViewController.h"

#import "Model.h"
#import "DataSource.h"
#import "TableViewCell.h"
#import "UIView+SDAutoLayout.h"
#import "UITableView+SDAutoTableViewCellHeight.h"

@interface ViewController ()<UITableViewDelegate>

@property (nonatomic, strong)NSArray *contentArray;
@property (nonatomic, strong)UITableView *tableView;
/// 这个要申明为 全局变量，否则会被释放
@property (nonatomic, strong)DataSource *dataSource;

@end

static NSString *const ID = @"cell";
@implementation ViewController
- (void)viewDidLoad
{
    [self.view addSubview:self.tableView];
    self.tableView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
    self.tableView.dataSource = self.dataSource;
}

#pragma table view delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:[self cellContentViewWith] tableView:tableView];
    return height;
}

- (CGFloat)cellContentViewWith
{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    
    // 适配ios7
    if ([UIApplication sharedApplication].statusBarOrientation != UIInterfaceOrientationPortrait && [[UIDevice currentDevice].systemVersion floatValue] < 8) {
        width = [UIScreen mainScreen].bounds.size.height;
    }
    return width;
}

#pragma mark - getter
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        _tableView.delegate = self;
    }
    return _tableView;
}

- (DataSource *)dataSource
{
    if (!_dataSource) {
        _dataSource = [[DataSource alloc] initWithItem:self.contentArray cellIdentifier:ID cellConfigBlock:^(TableViewCell *cell, Model *item, NSIndexPath *indexPath) {
            
            cell.model = item;
        }];
    }
    return _dataSource;
}

- (NSArray *)contentArray
{
    if (!_contentArray) {
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"Status" ofType:@"plist"];
        NSArray *arr = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *contentArray = [NSMutableArray array];
        
        [arr enumerateObjectsUsingBlock:^(NSDictionary *dic, NSUInteger idx, BOOL * _Nonnull stop) {
            Model *model = [Model modelWithDictionay:dic];
            [contentArray addObject:model];
        }];
        _contentArray = contentArray;
    }
    return _contentArray;
}

@end
